/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sistemadecompras.interfaz;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sistemadecompras.negocio.Factura;
import sistemadecompras.negocio.Producto;
import sistemadecompras.negocio.Productos;
import sistemadecompras.negocio.Venta;
import sistemadecompras.negocio.Ventas;


/**
 *
 * @author Pablo
 */
public class PanelVentas extends javax.swing.JPanel {

    int idfactura;
    Productos listaProductos = new Productos();
    Ventas listaVentas = new Ventas();
    Venta unaVenta = new Venta();
    Producto unProducto = new Producto();

    /**
     * Creates new form Ventas
     */
    public PanelVentas(int idfactura) {
        initComponents();
        this.idfactura = idfactura;
        txtnumFactura1.setText(idfactura + "");
        actualizaVentas();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        txtnumFactura1 = new javax.swing.JTextField();
        jLabel28 = new javax.swing.JLabel();
        btnAnadirProductoVenta = new javax.swing.JButton();
        btnEliminarClientes1 = new javax.swing.JButton();
        jLabel30 = new javax.swing.JLabel();
        txtProductoVenta = new javax.swing.JTextField();
        jScrollPane5 = new javax.swing.JScrollPane();
        tblProductos = new javax.swing.JTable();
        txtCantidadVenta = new javax.swing.JTextField();
        jLabel31 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtDesc = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();

        txtnumFactura1.setEnabled(false);
        txtnumFactura1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtnumFactura1ActionPerformed(evt);
            }
        });

        jLabel28.setText("Numero Factura");

        btnAnadirProductoVenta.setText("Añadir Producto a Factura");
        btnAnadirProductoVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnadirProductoVentaActionPerformed(evt);
            }
        });

        btnEliminarClientes1.setText("Eliminar Producto de Factura");
        btnEliminarClientes1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarClientes1ActionPerformed(evt);
            }
        });

        jLabel30.setText("Codigo Producto");

        txtProductoVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProductoVentaActionPerformed(evt);
            }
        });
        txtProductoVenta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtProductoVentaKeyPressed(evt);
            }
        });

        tblProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Producto", "Cantidad", "Precio (10% precio+, del prod en tabla porducto) TRIGGER", "Precio Dscto(precio ANTERIOR - X%) PROCEDIMIENTO ALMACENADO", "PrecioTotal"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblProductos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblProductosMouseClicked(evt);
            }
        });
        jScrollPane5.setViewportView(tblProductos);

        txtCantidadVenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCantidadVentaActionPerformed(evt);
            }
        });
        txtCantidadVenta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCantidadVentaKeyPressed(evt);
            }
        });

        jLabel31.setText("Cantidad");

        jLabel1.setText("Descuento");

        jButton1.setText("Aplicar Descuento");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("%");

        jLabel3.setText("TOTAL:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel31)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCantidadVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(373, 373, 373))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel28)
                            .addComponent(jLabel30))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(txtProductoVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnEliminarClientes1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(txtnumFactura1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnAnadirProductoVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(29, 29, 29)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addGap(83, 83, 83)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel28)
                    .addComponent(txtnumFactura1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAnadirProductoVenta))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel30)
                    .addComponent(txtProductoVenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminarClientes1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel31)
                    .addComponent(txtCantidadVenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(23, 23, 23)))
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(39, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtnumFactura1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnumFactura1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtnumFactura1ActionPerformed

    private void btnAnadirProductoVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnadirProductoVentaActionPerformed

        if (txtProductoVenta.getText().equals("") || txtCantidadVenta.getText().equals("")) {
            JOptionPane.showMessageDialog(jButton1, "Se debe completar todos los Campos");
        } else {
            unProducto.setId_prod(Integer.parseInt(txtProductoVenta.getText()));
            if (unProducto.buscar()) {
                if (unProducto.comprobarCantidad(Integer.parseInt(txtCantidadVenta.getText()))) {
                    unaVenta.setNumero(idfactura);
                    unaVenta.setCantidad(Integer.parseInt(txtCantidadVenta.getText()));
                    unaVenta.setId_prod(Integer.parseInt(txtProductoVenta.getText()));
                    boolean comP = false;
                    for (int i = 0; i < listaVentas.getVentas().size(); i++) {
                        if (((Venta) listaVentas.getVentas().get(i)).getId_prod() == unaVenta.getId_prod()) {
                            comP = true;
                        }
                    }
                    unProducto.setCantidad(unProducto.getCantidad() - unaVenta.getCantidad());
                    boolean r = false;
                    if (comP) {
                        unaVenta.buscar();
                        unaVenta.sumarCant(Integer.parseInt(txtCantidadVenta.getText()));
                        r = unaVenta.modificar();
                    } else {
                        r = unaVenta.grabar();
                    }
                    if (r == true) {
                        boolean modifica = unProducto.restarCantidad();
                        if (modifica) {
                            JOptionPane.showMessageDialog(jButton1, "Datos Grabados Exitosamente");
                            actualizaVentas();
                        } else {
                            JOptionPane.showMessageDialog(jButton1, "Error al Grabar datos");
                        }
                    } else {
                        JOptionPane.showMessageDialog(jButton1, "Error al Grabar datos");
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "No hay productos disponibles");
                }
            } else {
                JOptionPane.showMessageDialog(null, "Codigo de producto no encontrado");
            }
        }
    }//GEN-LAST:event_btnAnadirProductoVentaActionPerformed

    private void btnEliminarClientes1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarClientes1ActionPerformed
        // TODO add your handling code here:
        int fila = tblProductos.getSelectedRow();
        unaVenta.setId_prod((int)tblProductos.getValueAt(fila, 0));
        unaVenta.setNumero(idfactura);

        if (unaVenta.eliminar()) {
            JOptionPane.showMessageDialog(null, "Venta eliminada");
        } else {
            JOptionPane.showMessageDialog(null, "Erro al eliminar venta");
        }

        actualizaVentas();



    }//GEN-LAST:event_btnEliminarClientes1ActionPerformed

    private void txtProductoVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProductoVentaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtProductoVentaActionPerformed

    private void txtProductoVentaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProductoVentaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtProductoVentaKeyPressed

    private void tblProductosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblProductosMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_tblProductosMouseClicked

    private void txtCantidadVentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCantidadVentaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCantidadVentaActionPerformed

    private void txtCantidadVentaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantidadVentaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCantidadVentaKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        DescuentoVentas dv=new DescuentoVentas(Integer.parseInt(txtDesc.getText()),idfactura);
        dv.setVisible(true);
        
        
        actualizaVentas();
        Factura of=new Factura();
        of.setId_fact(idfactura);
        of.buscar();
        
        txtTotal.setText(of.getTotal()+"");
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void actualizaVentas() {

        listaVentas.buscar(txtnumFactura1.getText());
        ArrayList ventas = new ArrayList();
        ventas = listaVentas.getVentas();
        String[] codigos = new String[ventas.size()];

        for (int i = 0; i < ventas.size(); i++) {
            codigos[i] = String.valueOf(((Venta) (ventas.get(i))).getId_prod());
        }
        listaProductos.buscarCodigo(codigos);
        ArrayList productos = new ArrayList();
        productos = listaProductos.getProductos();
        DefaultTableModel temp = (DefaultTableModel) tblProductos.getModel();

        for (int i = tblProductos.getRowCount() - 1; i >= 0; i--) {
            temp.removeRow(i);
        }
        for (int i = 0; i < productos.size(); i++) {
            Producto otroProducto = new Producto();
            Venta otraVenta = new Venta();
            otroProducto = (Producto) productos.get(i);
            otraVenta = (Venta) ventas.get(i);
            //PARA EL DESCUENTO SE DEBERIA LLAMAR AL PROCEDIMIENTO ALMACENADO, descuento(otroProducto.getPrecio) que deberia retornar un valor de tipo real para ir llamando cada vez para cada producto :)
            //algo asi double preciodescto = descuento(otroProducto.getPrecio);
            Object nuevo[] = {otroProducto.getId_prod(), otroProducto.getProducto(), otraVenta.getCantidad(), otraVenta.getPrecio_v(),/*preciodescto*/" ",/*preciodescto*otroProducto.getPrecio()*/" " }; //esto es por las tres columnas aunque puede variar
            
            temp.addRow(nuevo);
        }
        tblProductos.setModel(temp);
        
        Factura of=new Factura();
        of.setId_fact(idfactura);
        of.buscar();
        
        txtTotal.setText(of.getTotal()+"");

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnadirProductoVenta;
    private javax.swing.JButton btnEliminarClientes1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable tblProductos;
    private javax.swing.JTextField txtCantidadVenta;
    private javax.swing.JTextField txtDesc;
    private javax.swing.JTextField txtProductoVenta;
    private javax.swing.JTextField txtTotal;
    private javax.swing.JTextField txtnumFactura1;
    // End of variables declaration//GEN-END:variables
}
